const express = require('express');
const router = express.Router();
const db = require('../db/db')

router.post('/api/answer', (req, res) => {
    let answer = new db.Answer.Model({
        _id: new db.Mongoose.Types.ObjectId(),
        content: req.body.content,
        author: req.session.user._id,
        questions: req.body.questionId,
        createTime: new Date()
    }).save().then(result => {
        console.log('回答问题成功', result)
        db.Question.Model.findById(result.questions).then((question) => {
            console.log('答案---查询对应问题', question)
            question.answers.push(result._id)
            question.save().then((saveQuestion) => {
                console.log('更新成功', saveQuestion)
                res.send({ code: 0, message: '回答成功' })
            })
        })
    }).catch(err => {
        console.log('回答问题失败', err)
    })
})

router.post('/api/like', (req, res) => {
    db.Answer.Model.findById(req.body.answerId)
        .then(answer => {
            answer.like += 1;
            answer.save().then(result => {
                console.log('点赞成功', result)
                res.send({ code: 0, message: '点赞成功' })
            })
        })
})

module.exports = router;